<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户详情</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-col :span="12">
                <!-- 登录表单区域 -->
                <div class="avatar">
                    <el-avatar size="large" :src="form.user_pic||circleUrl"></el-avatar>
                    <div>
                        <el-upload
                        class="upload-demo"
                        action=""
                        :show-file-list="false"
                        :on-change="getFile"
                        :auto-upload="false">
                            <el-button size="mini">更换头像</el-button>
                        </el-upload>
                    </div>
                </div>
                <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
                    <!-- 用户名 -->
                    <el-form-item prop="username" label="用户名">
                        <el-input :value="form.username" prefix-icon="el-icon-user" type="text" :disabled="true"></el-input>
                    </el-form-item>
                    <!-- 用户名 -->
                    <el-form-item prop="nickname" label="昵称">
                        <el-input v-model="form.nickname" prefix-icon="el-icon-user" placeholder="请输入昵称" :disabled="aditInfo"></el-input>
                    </el-form-item>
                    <!-- 用户名 -->
                    <el-form-item prop="email" label="邮箱">
                        <el-input v-model="form.email" prefix-icon="el-icon-user" placeholder="请输入邮箱" :disabled="aditInfo"></el-input>
                    </el-form-item>
                    <!-- 按钮区域 -->
                    <el-form-item class="btns">
                        <el-button type="primary" @click="editUserInfo">{{aditInfo?'编辑':'保存'}}</el-button>
                        <el-button v-show="!aditInfo" @click="cancelUser">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
            <!-- 注册表单区域 -->
            <el-col :span="12">
                <div class="avatar">密码</div>
                <el-form ref="pasdRef" :model="pasd" :rules="pasdRules" label-width="80px">
                    <!-- 原密码 -->
                    <el-form-item prop="oldPwd">
                        <el-input v-model="pasd.oldPwd" prefix-icon="el-icon-lock" :placeholder="checkPwd?'**************':'请输入原密码'" show-password :disabled="checkPwd" maxlength="12"></el-input>
                    </el-form-item>
                    <!-- 密码 -->
                    <el-form-item prop="newPwd" v-show="!checkPwd">
                        <el-input v-model="pasd.newPwd" prefix-icon="el-icon-lock" placeholder="请输入新密码" type="password" show-password maxlength="12"></el-input>
                    </el-form-item>
                    <!-- 确认密码 -->
                    <el-form-item prop="checkNewPwd" v-show="!checkPwd">
                        <el-input v-model="pasd.checkNewPwd" prefix-icon="el-icon-lock" placeholder="请确认新密码" type="password" show-password maxlength="12"></el-input>
                    </el-form-item>
                    <!-- 验证码 -->
                    <el-form-item prop="verCode" v-show="!checkPwd">
                        <el-col :span="14"><el-input v-model="pasd.verCode" prefix-icon="el-icon-edit-outline" placeholder="请输入验证码" maxlength="6"></el-input></el-col>
                        <el-col :span="10" @click.native="generateMixed(6)"><verCode :randomString="randomString"></verCode></el-col>
                    </el-form-item>
                    <!-- 按钮区域 -->
                    <el-form-item class="btns">
                        <el-button type="primary" @click="editPassWord">{{checkPwd?'更新':'保存'}}</el-button>
                        <el-button v-show="!checkPwd" @click="cancelPasd">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-card> 
    </div>
</template>

<script>
import { use } from '@/api/user.js';
import verCode from '@/components/verCode.vue'
export default {
    components: { verCode },
    data () {
        // 自定义校验规则 验证验证码
        var checkCode = (rule, value, cb) => value.toUpperCase() !== this.randomString.toUpperCase() ? cb(new Error('验证码错误')) : cb();
        // 自定义校验规则 验证密码
        var validatePass = (rule, value, cb) => {
            if (value === this.pasd.oldPwd) return cb(new Error('原密码不能和新密码一样'))
            if (this.pasd.checkNewPwd !== '') return this.$refs.pasdRef.validateField('checkNewPwd')
            return cb()
        };
        
        var validatePass2 = (rule, value, cb) => value !== this.pasd.newPwd ? cb(new Error('两次输入密码不一致!')) : cb();
        return {
            randomString: '',
            circleUrl: 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png',
            aditInfo: true,
            checkPwd: true,
            // 这是登录表单的数据绑定对象
            form: {},
            // 这是表单的验证规则对象
            formRules: {
                // 验证昵称是否合法
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                // 邮箱是否合法
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ]
            },
            pasd: {
                oldPwd: '',
                newPwd: '',
                checkNewPwd: '',
                verCode: ''
            },
            // 这是表单的验证规则对象
            pasdRules: {
                oldPwd: [
                    { required: true, message: '请输入原密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                ],
                newPwd: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkNewPwd: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                    { validator: validatePass2, trigger: 'blur' }
                ],
                // 验证验证码是否合法
                verCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 6, max: 6, message: '请输入6位验证码', trigger: 'blur' },
                    { validator: checkCode, trigger: 'blur' }
                ],
            }
        }
    },
    created () {

    },
    mounted () {
        this.getUserInfo()
    },
    methods: {
        // 获取初始用户信息
        async getUserInfo() {
            const { data: res } = await use.get()
            if (res.status !== 0) return this.$message.error(res.message)
            this.form = res.data
        },
        // 编辑用户信息
        async editUserInfo() {
            this.aditInfo = !this.aditInfo
            // 打开编辑  // 存储一下原始信息
            if (!this.aditInfo) return window.sessionStorage.setItem('userInfo', JSON.stringify(this.form))
            // 提交编辑 判断有没有改变,没有更改就不提交
            // 没有改变
            if (window.sessionStorage.getItem('userInfo') === JSON.stringify(this.form)) {
                this.aditInfo = !this.aditInfo
                return this.$message.error('您未做修改!')
            }
            // 改变了
            const { data: res } = await use.update(this.form)
            if (res.status !== 0) return this.$message.error(res.message)
            return this.$message.success(res.message)
        },
        // 用户操作重置
        cancelUser() {
            this.$refs.formRef.resetFields()
            this.form = JSON.parse(window.sessionStorage.getItem('userInfo'))
            this.aditInfo = !this.aditInfo
            return this.$message.info('已取消操作!')
        },
        // 编辑密码
        async editPassWord() {
            this.checkPwd = false
            // 提交编辑
            let flag = true
            this.$refs.pasdRef.validate(valid => {
                console.log('进来了', valid);
                if (!valid) flag = valid
            })
            if (!flag) return
            
            const { data: res } = await use.updatepwd(this.pasd)
            console.log('请求成功', res);
            if (res.status !== 0) return this.$message.error(res.message)
            this.$message.success(res.message)
            setTimeout(_ => this.$message.error('密码已更新，请重新登陆'),500)
            setTimeout(_ => {
                this.$store.commit('setUserToken', null)
                this.$router.push('/Login')
            },1000)
        },
        // 密码操作重置
        cancelPasd() {
            this.$refs.pasdRef.resetFields()
            this.checkPwd = true
            this.$message.info('已取消操作!')
        },
        // 更换头像
        async getFile(file) {
            const isJPG = file.raw.type === 'image/jpeg';
            const isPNG = file.raw.type === 'image/png';
            const isLt5M = file.raw.size / 1024 / 1024 < 5;
            if (!isJPG && !isPNG)return this.$message.error('上传图片只能是JPG或者PNG格式!');
            if (!isLt5M)return this.$message.error('上传图片大小不能超过 5MB!');
            if ((isJPG || isPNG) && isLt5M) {
                const picBase64 = await this.getBase64(file.raw)
                // console.log(picBase64)
                //这里拿到base64的文件流，处理业务逻辑
                const { data: res } = await use.avatar({ avatar: picBase64 })
                // console.log('请求', res);
                if (res.status !== 0) return this.$message.error(res.message)
                this.$message.success(res.message)
                this.form.user_pic = picBase64
            }
        },
        // 随机字符串
        generateMixed(n) {
            var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            var res = '';
            for (var i = 0; i < n; i++) {
                var id = Math.ceil(Math.random() * 35);
                res += chars[id];
            }
            this.randomString = res;
            // console.log(res.toUpperCase());
            return true
        },
        // 封装base64
        getBase64(file) {
            return new Promise(function(resolve, reject) {
                const reader = new FileReader();
                let imgResult = '';
                reader.readAsDataURL(file);
                reader.onload = function() {
                imgResult = reader.result;
                };
                reader.onerror = function(error) {
                reject(error);
                };
                reader.onloadend = function() {
                resolve(imgResult);
                };
            });
        },
    }
}
</script>

<style scoped lang="less">
/deep/.el-avatar:hover{
    background: rgba(0, 0, 0, .3);
}
/deep/.avatar{
    // width: 100%;
    text-align: center;
    margin:20px 80px;
}
/deep/.el-card{
  height: calc(100vh - 130px);
}

</style>
